package com.chanjet.donkey.component.saas;

import java.util.concurrent.atomic.AtomicLong;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

@Component
public class SaasHandlerInterceptor extends HandlerInterceptorAdapter {
	private static AtomicLong counter = new AtomicLong();
	
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) 
			throws Exception {
		System.out.println("----------- set tenant identifier");
		TenantUtil.setTenantId("dataSource0" + (counter.incrementAndGet() % 2 + 1));
		return super.preHandle(request, response, handler);
	}

	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		System.out.println("----------- clear tenant identifier");
		TenantUtil.setTenantId(null);
		super.afterCompletion(request, response, handler, ex);
	}

}
